#!/usr/bin/python
# -*- coding: UTF-8 -*-
import matplotlib.pyplot as plot
import numpy as np
import tushare as ts
from datetime import datetime
import pandas as pd
from matplotlib.finance import quotes_historical_yahoo_ohlc ,candlestick_ohlc,candlestick_ohlc
from matplotlib.pylab import date2num
# http://blog.sina.com.cn/s/blog_8fe936aa0102xfjw.html
# https://blog.csdn.net/u014281392/article/details/73611624
plot.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
plot.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题


def test2():
    hist_data = ts.get_hist_data('300311', start='2017-01-05', end='2017-05-05')
    print(hist_data.head(2))
    # 对tushare获取到的数据转换成candlestick_ohlc()方法可读取的格式
    data_list = []
    for dates, row in hist_data.iterrows():
        # 将时间转换为数字
        date_time = datetime.strptime(dates, '%Y-%m-%d')
        t = date2num(date_time)
        open, high, close, low ,volume= row[:4]
        datas = (t, open, high, low, close)
        data_list.append(datas)

    # 创建子图
    print(data_list)
    fig, ax = plot.subplots()
    fig.subplots_adjust(bottom=0.2)
    # 设置X轴刻度为日期时间
    ax.xaxis_date()
    plot.xticks(rotation=45)
    plot.yticks()
    candlestick_ohlc(ax,data_list,width=0.6,colordown="g",colorup="r",alpha=1)
    plot.title("股票代码：601558两年K线图")
    plot.xlabel("时间")
    plot.ylabel("股价（元）")

    plot.grid()
    plot.show()


hist_data = ts.get_hist_data('300311', start='2017-01-05', end='2017-05-05')

# 对tushare获取到的数据转换成candlestick_ohlc()方法可读取的格式

date_list=[]
voluem_list=[]
all_list=[]
for dates, row in hist_data.iterrows():
    # 将时间转换为数字
    date_time = datetime.strptime(dates, '%Y-%m-%d')
    t = date2num(date_time)
    open, high, close, low,volume = row[:5]
    datas = (t, open, high, low, close)
    all_list.append(datas)
    date_list.append(t)
    voluem_list.append(volume)


fig, (ax1, ax2) = plot.subplots(2, sharex=True, figsize=(15,8))

candlestick_ohlc(ax1, all_list, width=1.0, colorup = 'g', colordown = 'r')
ax1.set_title('wandayuanxian')
ax1.set_ylabel('Price')
# ax1.grid(True)
ax1.xaxis_date()
plot.fill_between(date_list, voluem_list)
# plot.bar(date_list, voluem_list, width= 0.5)
ax2.set_ylabel('Volume')
# ax2.grid(True)
plot.savefig("stock.jpg")
plot.show()